package com.java.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: java_basic_knowledge
 * @description:
 * @author: CaoYong
 * @create: 2021-04-07 13:27
 **/
public class JDKDynamicProxyDemo {

    public interface IService {
        public void sayHello();
    }

    static class RealService implements IService {
        @Override
        public void sayHello() {
            System.out.println("JDK Dynamic Hello");
        }
    }

    static class SimpleInvocationHandler implements InvocationHandler {
        private  Object realObj;

        public SimpleInvocationHandler(Object realObj) {
            this.realObj = realObj;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("before Hello");
            Object invoke = method.invoke(realObj, args);
            System.out.println("after Hello");
            return invoke;
        }
    }

    public static void main(String[] args) {
        IService iService = new RealService();
        // 使用java.lang.reflect包中的Proxy类的静态方法newProxyInstance构建代理对象
        // 1. 参数1为类加载器
        // 2. 参数2为代理类需要实现的接口列表
        // 3. InvocationHandler 定义了invoke()方法的接口，所有对代理接口方法的调用都会转给这个方法
        IService proxyService = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[] {IService.class}, new SimpleInvocationHandler(iService));
        proxyService.sayHello();
    }
}
